import {compose, lifecycle, withHandlers, withState} from "recompose"
import {postParam, putParam} from "server"
import download from "libs/download"
import {message, Modal} from 'antd'
import React from "react"
import {HOST} from "../../../../../shared/project-config"
import {rootPath} from "../../../../../shared/init"
import {read} from "zr-react-toolbox"
import {ExclamationCircleOutlined} from '@ant-design/icons'

//TODO:写得太乱了,需要重构

const timeoutPromise = (timeout) => {
	return new Promise((resolve => {
		setTimeout(resolve, timeout || 1000)
	}))
}

const countDownText = (expireTime) => {
	const remain = (expireTime - new Date().getTime()) / 1000
	let m = Math.floor(remain / 60)
	let s = Math.floor(remain % 60)
	let ms = m < 10 ? `0${m}` : m
	let ss = s < 10 ? `0${s}` : s
	return `${ms}分${ss}秒`
}

const orderCompose = compose(
	withState('payType', '$payType', (props) => {
		return read(props, "data.paymentType")
	}),
	withState('payTypeVisible', '$payTypeVisible', false),
	withState('submitPayTypeVisible', '$submitPayTypeVisible', true),
	withState('needPrint', '$needPrint', false),
	withState('payLoading', '$payLoading', false),
	withState('checkedFiles', '$checkedFiles', []),
	withState('receiver', '$receiver', null),
	withState('submitLoading', '$submitLoading', false),
	withState('countDown', '$countDown', (props) => {
		const {data} = props
		//1小时内
		const expireTime = data['expireTime']
		return expireTime - new Date().getTime() >= 0 ? countDownText(expireTime) : 0
	}),
	withHandlers({
		onSelectReceiver: ({$receiver}) => {
			return (data) => {
				$receiver(data)
			}
		},
		//改变是否打印
		//TODO:缓存计算结果
		onChangePrint: ({$needPrint, onNeedPrintChange}) => {
			return (checked) => {
				$needPrint(checked)
				if (onNeedPrintChange) onNeedPrintChange(checked)
			}
		},
		onPayTypeSelect: ({$payType}) => {
			return (event) => {
				$payType(event.target.value)
			}
		},
		toDownload: () => {
			return (downloadFile) => () => {
				download(`${HOST}/order/download?fileIds=${downloadFile.id}`)
			}
		},
		toBatchDownload: () => {
			return (files) => () => {
				const ids = files.map(f => f.id);
				download(`${HOST}/order/download?${ids.map(i => `fileIds=${i}`).join("&")}`)
			}
		},
		//选择文件
		onFileCheck: ({$checkedFiles, checkedFiles}) => {
			return (f) => (event) => {
				const checked = event.target.checked
				if (checked) {
					$checkedFiles(checkedFiles.concat(f))
				} else {
					$checkedFiles(checkedFiles.filter(i => i.id !== f.id))
				}
			}
		},
		//判断文件是否被选中
		isChecked: ({checkedFiles}) => {
			return (f) => {
				return checkedFiles.some(i => i.id === f.id)
			}
		}
	}),
	withHandlers({
		toSubmit: ({receiver, data, refreshOrder, $submitLoading, needPrint}) => {
			return () => {
				if (needPrint && !receiver) {
					message.error('请先填写收件人信息')
					return
				}
				$submitLoading(true)
				const postPromise = postParam(`/order/submit/${data.id}`, receiver ? {receiverId: receiver.id} : {})
				//避免过快提交
				Promise.all([postPromise, timeoutPromise(1200)])
					.then(res => {
						if (res) {
							message.success("订单提交成功")
							refreshOrder()
						}
					})
					.finally(() => {
						$submitLoading(false)
					})
			}
		},
		toPay: ({data, payType, refreshOrder, $payLoading, $payTypeVisible}) => {
			return () => {
				if (!payType) {
					message.error("请先选择支付方式")
					return
				}

				$payTypeVisible(false)
				$payLoading(true)

				const fetchPromise = postParam(`/order/toPay/${data.id}`, {payType})
					.then(() => {
							if (payType === 'ALI') {
								window.open(`${HOST}/order/alipay/${data.id}`, "_blank");
							}
							refreshOrder()
						}
					)
				Promise.all([fetchPromise, timeoutPromise()]).finally(() => {
					$payLoading(false)
					$payTypeVisible(true)
				})
			}
		},
		toChangePayType: ({data, payType, refreshOrder, $payLoading, $payTypeVisible}) => {
			return () => {
				$payTypeVisible(false)
				$payLoading(true)

				if (payType === 'ALI') {
					window.open(`${HOST}/order/alipay/${data.id}`, "_blank");
				}

				const fetchPromise = postParam(`/order/changePayType/${data.id}`, {payType})
					.then(() =>
						refreshOrder()
					)
				//避免闪烁
				Promise.all([fetchPromise, timeoutPromise()]).finally(() => $payLoading(false))

			}
		},
		toCancelOrder: ({data, history}) => {
			return () => {
				const content = <div>确认取消订单<b>{data['orderNo']}</b>吗？</div>
				Modal.confirm({
					title: '取消确认',
					icon: <ExclamationCircleOutlined/>,
					content: content,
					onOk: () => {
						putParam(`/order/cancel/${data.id}`)
							.then(data => {
								message.success(<span>订单 <b>${data['orderNo']}</b> 取消成功</span>)
								history.push(`/${rootPath}/library`)
							})
					}
				})
			}
		},
		toBack: ({history, onBack}) => {
			return () => {
				if (onBack) {
					onBack()
				} else {
					history.push(`/${rootPath}/my-order/history-order`)
				}
			}
		},
		//支付通知回调websocket
		onMessage: ({data}) => {
			return (m) => {
				if (m === 'SUCCESS') {
					let secondsToGo = 3
					const modal = Modal.success({
						title: '支付完成',
						content: `支付完成, ${secondsToGo + 1}秒内自动下载`,
						okText: '现在下载',
						cancelText: '暂不下载',
						onOk: () => {
							download(`${HOST}/order/download/${data.id}`)
						}
					})

					setInterval(() => {
						secondsToGo -= 1
						modal.update({
							content: `支付完成, ${secondsToGo + 1}秒内自动下载`,
						})
					}, 1000)

					setTimeout(() => {
						download(`${HOST}/order/download/${data.id}`)
						modal.destroy()
					}, secondsToGo * 1000)
					return
				}
			}
		}
	}),
	lifecycle({
		componentDidMount() {
			const {$countDown, data} = this.props
			const expireTime = data['expireTime']
			if (expireTime - new Date().getTime() > 0) {
				const timer = setInterval(() => {
					const expire = countDownText(expireTime)
					$countDown(expire)
					if (expireTime - new Date().getTime() <= 0) {
						clearInterval(timer)
					}
				}, 1000)
			}
		}
	})
)

export default orderCompose